#include "input.h"

#include "patch.h"
#include "quadrilateral.h"
#include "triangle.h"
#include "vector3D.h"
#include "material.h"
#include "color.h"

#include <fstream>

namespace t2c2 {
	
Input::Input(const char* _filename) : filename(_filename) {
}	
	
Input::Input(void) {
}		
	

Input::~Input(void) {
}

Scene* Input::parse(void) {
	std::ifstream fin(filename);
	char type;
	
	double x1,y1,z1;
	double x2,y2,z2;
	double x3,y3,z3;
	double x4,y4,z4;
	
	double r1,g1,b1;
	double r2,g2,b2;
	
	Scene* scene = new Scene(Color());
	
	Material* current_material = new Material(Color(),Color());
	
	unsigned int id = 0;
	
	while(fin >> type) {
		if(type == 'm') {
			fin >> r1 >> g1 >> b1 >> r2 >> g2 >> b2;
			Color emissivity(r1,g1,b1);
			Color reflectivity(r2,g2,b2);
			current_material = new Material(emissivity,reflectivity);
			continue;
		} else if(type == 't') {
			fin >> x1 >> y1 >> z1 >> x2 >> y2 >> z2 >> x3 >> y3 >> z3;
			Vector3D v1 (x1,y1,z1);
			Vector3D v2 (x2,y2,z2);
			Vector3D v3 (x3,y3,z3);
			Material* material = new Material();
			material->set_emissivity(current_material->get_emissivity());
			material->set_reflectivity(current_material->get_reflectivity());
			Triangle* triangle = new Triangle(material,v1,v2,v3);
			triangle->set_id(id);
			scene->add_patch(triangle);
			continue;
		} else if(type == 'q') {
			fin >> x1 >> y1 >> z1 >> x2 >> y2 >> z2 >> x3 >> y3 >> z3 >> x4 >> y4 >> z4;
			Vector3D v1 (x1,y1,z1);
			Vector3D v2 (x2,y2,z2);
			Vector3D v3 (x3,y3,z3);
			Vector3D v4 (x4,y4,z4);
			Material* material = new Material();
			material->set_emissivity(current_material->get_emissivity());
			material->set_reflectivity(current_material->get_reflectivity());
			Quadrilateral* quadrilateral = new Quadrilateral(material,v1,v2,v3,v4);
			quadrilateral->set_id(id);
			scene->add_patch(quadrilateral);
			continue;
		} else if(type == '#') {
			//Comments!
			char* a;
			fin.getline(a,100,'\n');
			continue;	
		}
		else if(type == 'p') {
			fin >> id;
		continue;	
		}
	}
	return scene;
}

Scene* Input::parse(const char* _filename) {
	filename = _filename;
	return parse();
}

}
